<?php

namespace AdminPanel\QuestionBundle\Controller;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;

use AdminPanel\QuestionBundle\Entity\ExamQuestion;
use AdminPanel\QuestionBundle\Form\ExamQuestionType;

use AdminPanel\QuestionBundle\Entity\ExamAnswer;
use AdminPanel\QuestionBundle\Entity\ExamAnswerMap;
/**
 * ExamQuestion controller.
 *
 */
class ExamQuestionController extends Controller
{
    /**
     * Lists all ExamQuestion entities.
     *
     */
    public function indexAction()
    {
        $em = $this->getDoctrine()->getManager();

        $entities = $em->getRepository('AdminPanelQuestionBundle:ExamQuestion')->findAll();        
        return $this->render('AdminPanelQuestionBundle:ExamQuestion:index.html.twig', array(
            'entities' => $entities,
        ));
    }

    /**
     * Finds and displays a ExamQuestion entity.
     *
     */
    public function showAction($id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('AdminPanelQuestionBundle:ExamQuestion')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find ExamQuestion entity.');
        }

        $deleteForm = $this->createDeleteForm($id);

        return $this->render('AdminPanelQuestionBundle:ExamQuestion:show.html.twig', array(
            'entity'      => $entity,
            'delete_form' => $deleteForm->createView(),        ));
    }

    /**
     * Displays a form to create a new ExamQuestion entity.
     *
     */
    public function newAction()
    {
        $entity = new ExamQuestion();
        $form   = $this->createForm(new ExamQuestionType(), $entity);

        return $this->render('AdminPanelQuestionBundle:ExamQuestion:new.html.twig', array(
            'entity' => $entity,
            'form'   => $form->createView(),
        ));
    }

    /**
     * Creates a new ExamQuestion entity.
     *
     */
    public function createAction(Request $request)
    {
        $entity  = new ExamQuestion();
        $form = $this->createForm(new ExamQuestionType(), $entity);
        $form->bind($request);

        if ($form->isValid()) {
          
            $entity->setCreatedAt(new \DateTime);
            $entity->setUpdatedAt(new \DateTime);
          
            
            
            $em = $this->getDoctrine()->getManager();
            $em->persist($entity);
            $em->flush();
            
            $this->saveAnswers($entity->getId());
            
            return $this->redirect($this->generateUrl('admin_question_edit', array('id' => $entity->getId())));            
        }

        return $this->render('AdminPanelQuestionBundle:ExamQuestion:new.html.twig', array(
            'entity' => $entity,
            'form'   => $form->createView(),
        ));
    }

    /**
     * Displays a form to edit an existing ExamQuestion entity.
     *
     */
    public function editAction($id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('AdminPanelQuestionBundle:ExamQuestion')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find ExamQuestion entity.');
        }

        $editForm = $this->createForm(new ExamQuestionType(), $entity);
        $deleteForm = $this->createDeleteForm($id);

        
        $questionArray = $this->findAnswerMap($id);
        
        if($questionArray)
        {
          $count = count($questionArray);
        }else{
          $count = null;
        }
        
        return $this->render('AdminPanelQuestionBundle:ExamQuestion:edit.html.twig', array(
            'entity'      => $entity,
            'form'   => $editForm->createView(),
            'delete_form' => $deleteForm->createView(),
            'questionArray' => $questionArray,
            'count' => $count
        ));
    }

    /**
     * Edits an existing ExamQuestion entity.
     *
     */
    public function updateAction(Request $request, $id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('AdminPanelQuestionBundle:ExamQuestion')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find ExamQuestion entity.');
        }

        $deleteForm = $this->createDeleteForm($id);
        $editForm = $this->createForm(new ExamQuestionType(), $entity);
        $editForm->bind($request);

        if ($editForm->isValid()) {
            $em->persist($entity);
            $em->flush();
            
            // save answers
            $this->saveAnswers($entity->getId());
            
            return $this->redirect($this->generateUrl('admin_question'));
        }

        return $this->render('AdminPanelQuestionBundle:ExamQuestion:edit.html.twig', array(
            'entity'      => $entity,
            'edit_form'   => $editForm->createView(),
            'delete_form' => $deleteForm->createView(),
        ));
    }

    /**
     * Deletes a ExamQuestion entity.
     *
     */
    public function deleteAction(Request $request, $id)
    {
        $form = $this->createDeleteForm($id);
        $form->bind($request);

        if ($form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $entity = $em->getRepository('AdminPanelQuestionBundle:ExamQuestion')->find($id);

            if (!$entity) {
                throw $this->createNotFoundException('Unable to find ExamQuestion entity.');
            }

            $em->remove($entity);
            $em->flush();
        }

        return $this->redirect($this->generateUrl('admin_Question'));
    }

    private function createDeleteForm($id)
    {
        return $this->createFormBuilder(array('id' => $id))
            ->add('id', 'hidden')
            ->getForm()
        ;
    }
    
    private function saveAnswers($questionId)
    {
      $answers[] = $_POST['answers']; 
      $answers = $answers[0];
      
      if(isset($_POST['is_correct'])){
        $isCorrect = $_POST['is_correct'];
      }else{
        $isCorrect = null;
      }
      
      
      
      $this->deleteOldMap($questionId);
      
      $em = $this->getDoctrine()->getManager();
      foreach($answers AS $answer)
      {
        
        $newAnswer = new ExamAnswer();
        $newAnswer->setAnswer($answer);
        $newAnswer->setIsActive(1);
        $newAnswer->setSortOrder(null);
        $newAnswer->setShowType('normal');
        $newAnswer->setAnswerType('radio');
        $newAnswer->setCreatedAt(new \DateTime());
        $newAnswer->setUpdatedAt(new \DateTime());
        
        $em->persist($newAnswer);
        $em->flush();
      
        
        $newExamAnswerMap = new ExamAnswerMap();
        $newExamAnswerMap->setQuestionId((int) $questionId);
        $newExamAnswerMap->setAnswerId((int) $newAnswer->getId());
        $newExamAnswerMap->setIsActive(1);
        if($answer == $isCorrect) {
          $newExamAnswerMap->setIsCorrect(1);
        }
        $newExamAnswerMap->setCreatedAt(new \DateTime());        
        $em->persist($newExamAnswerMap);
        $em->flush();
        
      }
      
    }
    
    private function deleteOldMap($questionId)
    {
      $mapObjects = $this->getDoctrine()->getManager()->getRepository('AdminPanelQuestionBundle:ExamAnswerMap')->findBy(array('questionId' => $questionId));
      
      if($mapObjects)
      {        
        $em = $this->getDoctrine()->getManager();
        foreach($mapObjects AS $object)
        {
          $em->remove($object);
          $em->flush();
        }
        
        return true;
        
      }else{
        return false;
      }
    }


    private function findAnswerMap($questionId)
    {
      $mapArray = $this->getDoctrine()->getManager()->getRepository('AdminPanelQuestionBundle:ExamAnswerMap')->findAllByQuestionId($questionId);
      if($mapArray)
      {
        return $mapArray;
      }else{
        return null;
      }
    }
}
